import { selfDetectInfo } from '../../services/inspect'
import Toast from '@vant/weapp/toast/toast'
import { controlDoCommand, querySpaceGroupData, controlCommandResult } from '../../services/inspect'
import dayjs from 'dayjs'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:"",
    orderId:"",
    vehicleId:"",
    instId:"",
    vehicleInfo: {},
    spaceId:"",
    cmdId:"",
    timer: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options){
      return
    }
    let vehicleId = options.vehicleId
    
    this.setData({
      vehicleId
    })
    // if(vehicleId){
    //   this.getVehicleDetail(vehicleId)
    // }
  },

  onShow(){
    // let orderId = this.data.orderId
    // let type = this.data.type
    let spaceId = wx.getStorageSync(`spaceId`) || ""
    this.setData({
      spaceId
    })
    if(spaceId){
      let queryData = {
        spaceId,
        url: "chargeRecord",
      }
      this.handleGetGroupVarId(queryData)
    }
  },

  onHide(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  onUnload(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
  },

  async handleSelfDetectInfo(data){
    // this.handleControlDoCommand()
    let res = await selfDetectInfo(data)
    console.log("res...", res)
    if(res.code == 200){
      let code = data.code
      let url = `/pages/inspect-charging/inspect-charging?spaceId=${code}`
      wx.navigateTo({
        url,
      })
    } else {
      Toast.fail(res.msg)
    }
  },

  async handleGetGroupVarId(data, doCommand){
    let resp = await querySpaceGroupData(data)
    console.log("resp>>>", resp)
    let spaceVarId = resp.rows[0].id
    console.log("spaceVarId>>>", spaceVarId)
    if(spaceVarId){
      this.setData({
        spaceVarId
      })

      if(doCommand){
        this.handleControlDoCommand()
      }
    }
  },

  async handleGetVarIdDoCommand(data, selfData){
    let resp = await querySpaceGroupData(data)
    console.log("resp>>>", resp)
    let spaceVarId = resp.rows[0].id
    console.log("spaceVarId>>>", spaceVarId)
    if(spaceVarId){
      this.setData({
        spaceVarId
      })
      this.handleControlDoCommand(selfData)
    }
  },


  // 随机数
  getUuid () {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
  },

  async handleControlDoCommand(selfData){
    let cmdId = this.getUuid()
    let spaceId = this.data.spaceId
    let varId = this.data.spaceVarId
    let cutDownNum = 60
    this.setData({
      cmdId
    })
    let doCommandData = {
      cmdId,
      spaceId,
      varId,
      cmdType: "Cmd_RelayExecute",
      cmdValue: '1'
    }
    wx.setStorageSync(`${spaceId}-doCommandData`, doCommandData)
    let resDoCommand = await controlDoCommand(doCommandData)
    if(resDoCommand.code == 200){
      wx.showLoading({
        title: '加载中',
      })
      this.handleSetInter(cutDownNum, selfData)
      this.handleGetCommandResult(selfData)
    }
  },

  async handleSetInter(cutDownNum, selfData){
    let cutNum = cutDownNum
    // if(this.data.timer){
    //   clearInterval(this.data.timer)
    // }
    const _this = this
    let timer = setInterval(function(){
      cutNum--
      _this.handleGetCommandResult(selfData)
      if(cutNum == 0){
        clearInterval(timer)
      }
    }, 1000)
    this.setData({
      timer
    })
  },

  async handleGetCommandResult(selfData){
    let cmdId = this.data.cmdId
    let spaceId = this.data.spaceId
    let res = await controlCommandResult({cmdId})
    if(res.data && res.data.result){
      let commandResult = res.data.result
      if(commandResult == 'Cmd_Result_Success'){
        wx.setStorageSync(`${spaceId}-yaokong`, true)
        wx.setStorageSync(`${spaceId}-yaokong-time`, dayjs().format('YYYY-MM-DD HH:mm:ss'))
        this.handleSelfDetectInfo(selfData)
      } else if(commandResult == 'Cmd_Result_Fail') {
        Toast.fail('执行失败!')
      } else if(commandResult == 'Cmd_Result_TimeOut') {
        Toast.fail('执行超时!')
      }
      wx.hideLoading()
      if(this.data.timer){
        clearInterval(this.data.timer)
      }
    }
  },

  handleNext(){
    let url = ""
    let vehicleId = this.data.vehicleId
    let code = wx.getStorageSync(`spaceId`) || ''
    let ykIsOk = false
  
    if(code){
      ykIsOk = wx.getStorageSync(`${code}-yaokong`) || false
      if(ykIsOk){
        this.handleSelfDetectInfo({
          vehicleId,
          code,
        })
      } else  {
        this.handleControlDoCommand({
          vehicleId,
          code,
        })
      }
      // this.handleSelfDetectInfo({
      //   vehicleId,
      //   code,
      // })
      
      // url = `/pages/inspect-charging/inspect-charging?spaceId=${code}`
      // wx.navigateTo({
      //   url,
      // })
    }else {
      const _this = this
      wx.scanCode({
        success (res) {
          let codeRes = res.result
          const qList = codeRes.split('/')
          let code = qList[qList.length - 1]
          console.log("spaceId>>>", code)
          _this.setData({
            spaceId: code
          })
          wx.setStorageSync(`spaceId`, code)
          wx.removeStorageSync(`charging-init-start-soc`)
          ykIsOk = wx.getStorageSync(`${code}-yaokong`) || false
          if(ykIsOk){
            _this.handleSelfDetectInfo({
              vehicleId,
              code,
            })
          } else {
            let queryData = {
              spaceId: code,
              url: "chargeRecord",
            }
            _this.handleGetVarIdDoCommand(queryData, {
              vehicleId,
              code,
            })
            // _this.handleControlDoCommand({
            //   vehicleId,
            //   code,
            // })
          }
          // url = `/pages/inspect-charging/inspect-charging?spaceId=${code}`
          // wx.navigateTo({
          //   url,
          // })
        }
      })
    }
  },

  handleScan(){
    let url = ""
    // let type = this.data.type
    // let orderId = this.data.orderId
    let vehicleId = this.data.vehicleId
    // let instId = this.data.instId
    console.log("重新扫码了>>>>")
    const _this = this
      wx.scanCode({
        success (res) {
          let codeRes = res.result
          console.log("codeRes>>>", codeRes)
          const qList = codeRes.split('/')
          let code = qList[qList.length - 1]
          console.log("spaceId>>>", code)
          _this.setData({
            spaceId: code
          })
          wx.setStorageSync(`spaceId`, code)
          wx.removeStorageSync(`charging-init-start-soc`)
          let ykIsOk = wx.getStorageSync(`${code}-yaokong`) || false

          if(ykIsOk){
            _this.handleSelfDetectInfo({
              vehicleId,
              code,
            })
          } else {
            let queryData = {
              spaceId: code,
              url: "chargeRecord",
            }
            _this.handleGetVarIdDoCommand(queryData, {
              vehicleId,
              code,
            })

            // _this.handleControlDoCommand({
            //   vehicleId,
            //   code,
            // })
          }
          // url = `/pages/inspect-charging/inspect-charging?spaceId=${code}`
          // wx.navigateTo({
          //   url,
          // })
        }
      })
  },

})